<template>
  <div class="app-container">
    <el-dialog :title="'定制下单'+tabName" :visible.sync="dialogVisible" width="60%" append-to-body
               :close-on-click-modal="false">
      <div class="tabDivs" v-if="tabIndex==0">
        <div class="tabDiv" v-for="item in goodList" @click="changeGood(item)">{{ item.productName }}</div>
      </div>
      <div v-if="tabIndex!=0" v-loading="loading">
        <el-form ref="form" :model="form">
          <div class="myTitle">基本信息</div>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="订单编号" prop="orderNo">
                <el-input v-model="form.orderNo" placeholder="自动生成" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产方式" prop="productFrom" required>
                <el-select v-model="form.productFrom" disabled style="width: 100%">
                  <el-option
                    v-for="item in dict.type.basic_good_source"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="来源平台" prop="orderFrom" required>
                <el-select v-model="form.orderFrom" filterable style="width: 100%">
                  <el-option
                    v-for="item in dict.type.ims_source_platform"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="源平台单号" prop="sourceOrderNo">
                <el-input v-model="form.sourceOrderNo" placeholder="请输入"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="加急单" prop="urgent" required>
                <el-select v-model="form.urgent" style="width: 100%">
                  <el-option
                    v-for="item in dict.type.sys_yes_no"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户图纸" prop="cusFileUrl">
                <div>
                  <div v-if="form.cusFileUrl" style="display: flex; align-items: center;cursor: pointer;">
                    <el-link type="primary">{{ form.cusFileName }}</el-link>
                    <i class="el-icon-close closeDiv" @click="form.cusFileUrl=null;form.cusFileName=null"></i>
                  </div>
                  <el-upload
                    v-else
                    :headers="headers"
                    :action="action2"
                    :on-success="uploadSuccess2"
                    :on-progress="uploadProgress"
                    :show-file-list="false"
                  >
                    <el-button type="primary" plain>点击上传</el-button>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样稿图片" prop="imageUrl">
                <div style="display: flex">
                  <div v-for="item in imgList">
                    <div class="myImg" style="margin-right: 10px">
                      <i class="el-icon-close" @click="imgList=imgList.filter(e=>e!=item)"></i>
                      <el-image
                        style="width: 150px;height: 150px"
                        :src="item"
                        fit="contain"
                        :preview-src-list="[item]"
                      >
                      </el-image>
                    </div>
                  </div>
                  <el-upload
                    v-if="imgList<3"
                    :headers="headers"
                    :action="action"
                    :on-success="uploadSuccess"
                    :on-progress="uploadProgress"
                    :show-file-list="false"
                    accept=".jpg,.jpeg,.png"
                    multiple
                    :limit="3"
                  >
                    <el-button type="primary" plain>点击上传</el-button>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="myTitle">规格信息</div>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="规格名称" prop="skuId" required>
                <el-select v-model="form.skuId" filterable style="width: 100%" @change="changeSku">
                  <el-option
                    v-for="item in skuNameList"
                    :key="item.skuId"
                    :label="item.skuName"
                    :value="item.skuId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品单价(元)" prop="unitPrice">
                <el-input type="number" v-model="form.unitPrice" placeholder="自动生成" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单数量" prop="amount" required>
                <el-input type="number" v-model="form.amount" min="1" placeholder="请输入"
                          @change="getPrice"/>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="skuList&&skuList.length">
            <div class="myTitle">定制信息</div>
            <el-form ref="skuForm" :model="skuForm">
              <div style="display: flex;flex-wrap: wrap;">
                <div v-for="val in skuList.filter(e=>e.isPrice==1)" style="width: 24%;margin-right: 10px">
                  <el-form-item :label="val.attributeName+(val.unit?'('+val.unit+')':'')" :prop="val.attributeKey"
                                :required="val.isMust==0">
                    <el-select v-if="val.skuValueList&&val.skuValueList.length" v-model="skuForm[val.attributeKey]"
                               filterable
                               style="width: 100%">
                      <el-option
                        v-for="item in val.skuValueList"
                        :key="item.value"
                        :label="item.value"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input v-else v-model="skuForm[val.attributeKey]" placeholder="请输入"/>
                  </el-form-item>
                </div>
              </div>
            </el-form>
          </div>
          <div>
            <div class="myTitle">配件信息</div>
            <el-button type="primary" plain @click="matList.push({quantity:1})">新增</el-button>
            <el-button plain @click="matList=[]">清空</el-button>
            <el-table
              :data="matList"
              max-height="500"
            >
              <el-table-column type="index" label="序号" align="center"></el-table-column>
              <el-table-column prop="productName" label="配件名称" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.productId" filterable @change="changeMat(scope.row.productId,scope.row)"
                             style="width: 100%">
                    <el-option
                      v-for="item in matSelect"
                      :key="item.productId"
                      :label="item.productName"
                      :value="item.productId">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="imageUrl" label="图片" align="center">
                <template slot-scope="scope">
                  <div v-if="!scope.row.imageUrl">暂无</div>
                  <el-image
                    v-else
                    style="width: 80px;height: 80px"
                    :src="scope.row.imageUrl"
                    fit="contain"
                    :preview-src-list="[scope.row.imageUrl]"
                  >
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="skuName" label="规格名称" align="center"/>
              <el-table-column prop="unitPrice" label="单价(元)" align="center" width="120"/>
              <el-table-column prop="quantity" label="数量" align="center" width="120">
                <template slot-scope="scope">
                  <el-input type="number" v-model="scope.row.quantity" placeholder="请输入" :min="0"
                            :max="scope.row.inventoryQuantity" @change="getPrice"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="inventoryQuantity" label=库存数量 align="center" width="120">
                <template slot-scope="scope">
                  <div>{{ scope.row.inventoryQuantity }}</div>
                </template>
              </el-table-column>
              <el-table-column label='删除' align="center" width="80">
                <template slot-scope="scope">
                  <el-button type="text" @click="deleteMat(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="myTitle">收件人信息</div>
            <el-button type="primary" plain @click="getAddrMsg">地址识别</el-button>
            <el-row :gutter="10">
              <el-col :span="16">
                <el-form-item label="收件人信息" prop="recipientContent" required>
                  <el-input type="textarea" v-model="form.recipientContent"
                            placeholder="参考格式：张三**省**市**区**街道**小区13088888888"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="姓名" prop="recipient" required>
                  <el-input v-model="form.recipient" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="电话" prop="recipientTel" required>
                  <el-input v-model="form.recipientTel" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址" prop="fullName" required>
                  <el-input v-model="form.fullName" placeholder="请输入"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div>
            <div class="myTitle">付款信息</div>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="商品价格(元)" prop="goodsPrice">
                  <div>{{ form.goodsPrice || '-' }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="配件价格(元)" prop="matPartPrice">
                  <div>{{ form.matPartPrice || '-' }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合计价格(元)" prop="totalPrice">
                  <div>{{ form.totalPrice || '-' }}</div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="出单备注" prop="printRemark">
                <el-input type="textarea" v-model="form.printRemark" placeholder="请输入"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="dialogOk" v-if="tabIndex">下 单</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from "../../../utils/auth";
import {
  submitCustomOrder,
  listGood, getCommonCode, getAddrMsg
} from "../../../api/imsMng";
import {getGoodSku, listGoodPart, listGoodSkuById} from "../../../api/goodMng";
import {listExpressShop} from "../../../api/expressMng";


export default {
  dicts: ['ims_source_platform', 'basic_good_source', 'sys_yes_no'],
  data() {
    return {
      tabIndex: 0,
      tabName: '',
      loading: false,
      dialogVisible: false,
      form: {},
      skuForm: {},
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      imgList: [],
      goodList: [],
      action: process.env.VUE_APP_BASE_API + '/ims/product/image/upload',
      action2: process.env.VUE_APP_BASE_API + '/ims/product/file/upload',
      attrList: [],
      provinceList: [],
      cityList: [],
      matList: [],
      skuList: [],
      matSelect: [],
      skuNameList: [],
      expressList: []
    }
  },
  methods: {
    show() {
      this.dialogVisible = true
      this.form = {}
      this.skuForm = {}
      this.resetForm('form')
      this.resetForm('skuForm')
      this.tabIndex = 0
      this.tabName = ''
      this.skuList = []
      this.matList = []
      this.imgList = []
      this.$set(this.form, 'amount', 1)
      this.$set(this.form, 'urgent', '1')
      this.$set(this.form, 'productFrom', '2')
      this.$set(this.form, 'orderType', '10')
      this.load()
    },
    load() {
      getCommonCode({orderType: 10}).then(res => {
        this.$set(this.form, 'orderNo', res.data.orderNo)
      })
      listGood({productType: 1, productSource: 2, pageSize: -1}).then(res => {
        this.goodList = res.rows
      })
      listExpressShop({pageSize: -1}).then(res => {
        this.expressList = res.rows
      })
    },
    changeMat(e, row) {
      let list = this.matSelect.filter(val => val.productId == e)
      row.productName = list[0].productName
      row.imageUrl = list[0].imageUrl
      row.skuName = list[0].skuName
      row.unitPrice = list[0].unitPrice
      row.inventoryQuantity = list[0].inventoryQuantity
      this.getPrice()
    },
    deleteMat(row) {
      this.matList = this.matList.filter(e => e != row)
      this.getPrice()
    },
    getAddrMsg() {
      let req = {
        recipientContent: this.form.recipientContent
      }
      this.loading = true
      getAddrMsg(req).then(res => {
        let data = res.data
        this.$set(this.form, 'recipient', data.recipient)
        this.$set(this.form, 'recipientTel', data.recipientTel)
        this.$set(this.form, 'fullName', data.fullName)
      }).finally(e => {
        this.loading = false
      })
    },
    changeGood(item) {
      this.tabIndex = item.id
      this.tabName = '（' + item.productName + '）'
      this.form.productId = item.id
      // 规格
      listGoodSkuById({productId: this.form.productId, productSource: 2}).then(res => {
        this.skuNameList = res.data
      })
      listGoodPart({productId: this.form.productId, productSource: 2, pageSize: -1}).then(res => {
        this.matSelect = res.rows;
      })
    },
    changeSku(e) {
      if (e) {
        this.skuList = []
        this.skuForm = {}
        this.resetForm('skuForm')
        let obj = this.skuNameList.filter(val => val.skuId == e)[0]
        this.$set(this.form, 'unitPrice', obj.unitPrice)
        this.getPrice()
      }
      getGoodSku(this.form.skuId).then(res => {
        let list = res.data.skuAttrRelationList
        list.map(val => {
          val[val.attributeKey] = val.value
          if (val.value) {
            this.$set(this.skuForm, val.attributeKey, val.value)
          }
        })
        this.skuList = JSON.parse(JSON.stringify(list))
      })
    },
    getPrice() {
      let goodPrice = (Number(this.form.unitPrice) || 0) * (Number(this.form.amount) || 0)
      let matPartPrice = 0
      this.matList.map(e => {
        matPartPrice = matPartPrice + (Number(e.unitPrice) || 0) * (Number(e.quantity) || 0)
      })
      let totalPrice = goodPrice + matPartPrice
      this.$set(this.form, 'goodsPrice', goodPrice)
      this.$set(this.form, 'matPartPrice', matPartPrice)
      this.$set(this.form, 'totalPrice', totalPrice)
    },
    uploadProgress() {
      this.loading = true
    },
    uploadSuccess(res) {
      this.loading = false
      if (res.code == 200) {
        this.imgList.push(res.data.imageUrl)
      } else {
        this.$message.error(res.msg)
      }
    },
    uploadSuccess2(res) {
      this.loading = false
      if (res.code == 200) {
        this.$set(this.form, 'cusFileUrl', res.data.fileUrl)
        this.$set(this.form, 'cusFileName', res.data.fileName)
      } else {
        this.$message.error(res.msg)
      }
    },
    dialogOk() {
      this.$refs.form.validate(e => {
        if (e) {
          let req = JSON.parse(JSON.stringify(this.form))
          req.customerOrderMatPartBoList = this.matList
          req.skuDesc = JSON.stringify(this.skuForm)
          req.imageUrls = this.imgList
          this.loading = true
          submitCustomOrder(req).then(res => {
            this.$emit('ok')
            this.dialogVisible = false
            this.$message.success('提交成功')
            this.$router.push('/orderMng/orderMng')
          }).finally(e => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.tabDivs {
  display: flex;
  justify-content: space-around;
}

.tabDiv {
  width: 300px;
  height: 200px;
  border: 1px solid;
  text-align: center;
  line-height: 200px;
  font-size: 20px;
  font-weight: bold;
  background: #0275a1;
  color: #fff;
  border-radius: 20px;
}

.tabDiv:nth-child(2) {
  background: #11b95c;
}

.tabDiv:nth-child(3) {
  background: #d742e6;
}

.tabDiv:hover {
  cursor: pointer;
  transform: scale(1.1);
}

.closeDiv {
  color: red;
  margin-left: 10px
}
</style>
